package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * 老人家属Service业务层处理
 * 
 * @author lxr
 * @date 2025-08-20
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private  WechatServiceImpl wechatService;
    @Autowired
    private TokenService tokenService;


    @Override
    public LoginVo login(UserLoginRequestDto usrDto) {
        // 1.调用小程序登录接口获取openid
        String openid = wechatService.getOpenid(usrDto.getCode());


        //2.根据openid查询数据库老人家属信息
        FamilyMember member = this.lambdaQuery()
                .eq(FamilyMember::getOpenId, openid)
                .one();

        //3.判断老人家属是否存在
        if(Objects.isNull(member)){
            member = new FamilyMember();
            member.setOpenId(openid);

        }

        //4.调用小程序获取手机号接口获取手机号
        String phone = wechatService.getPhone(usrDto.getPhoneCode());
        member.setPhone(phone);
        String nickName = Constants.DEFAULT_NICKNAME_PREFIX
                .get(RandomUtil.randomInt(0, Constants.DEFAULT_NICKNAME_PREFIX.size()))
                .concat(phone.substring(phone.length() - 4));
        if(StringUtils.isBlank(member.getRemark())){
            member.setRemark(nickName);
        }


        //5.新增或更新用户信息
        saveOrUpdateFamilyMember(member);

        //6.封装数据(家属id和昵称)
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("memberId", member.getId());
        claims.put("nickName", member.getRemark());
        String token=tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getRemark());
        return loginVo;
    }

    private void saveOrUpdateFamilyMember(FamilyMember member) {
        if(Objects.isNull(member.getId())){
            save(member);
        }else{
            updateById(member);
        }

    }
}
